package com.example.seabedmusic.views;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.seabedmusic.R;
import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.presenter.MusicPresenter;

import java.util.ArrayList;
import java.util.List;

public class SuiJiFragment extends Fragment implements MusicContract.IMusicView {

    private MusicContract.IMusicPresenter mPresenter;
    private Button btnRandom;
    private ImageView ivCover;
    private TextView tvSongName, tvArtist, tvAlbum;
    private List<Song> currentSongList = new ArrayList<>();
    private View songInfoLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_suiji, container, false);

        // 初始化视图
        btnRandom = root.findViewById(R.id.btn_random);
        ivCover = root.findViewById(R.id.iv_cover);
        tvSongName = root.findViewById(R.id.tv_song_name);
        tvArtist = root.findViewById(R.id.tv_artist);
        tvAlbum = root.findViewById(R.id.tv_album);
        songInfoLayout = root.findViewById(R.id.song_info_layout);

        // 初始化Presenter
        mPresenter = new MusicPresenter(this, getContext());

        // 设置随机按钮点击事件
        btnRandom.setOnClickListener(v -> {
            mPresenter.getRandomMusic();
        });

        // 设置封面点击事件，点击封面跳转到播放页面
        ivCover.setOnClickListener(v -> {
            if (!currentSongList.isEmpty()) {
                playSong(currentSongList.get(0));
            }
        });

        return root;
    }

    @Override
    public void showSongs(List<Song> songs) {
        if (songs != null && !songs.isEmpty()) {
            currentSongList.clear();
            currentSongList.addAll(songs);

            Song song = songs.get(0);

            // 显示歌曲信息区域
            if (songInfoLayout != null) {
                songInfoLayout.setVisibility(View.VISIBLE);
            }

            // 更新UI
            tvSongName.setText(song.getTitle());
            tvArtist.setText(song.getArtist());
            tvAlbum.setText(song.getAlbum() != null ? song.getAlbum() : "未知专辑");
            tvAlbum.setText(song.getAlbum() != null ? song.getAlbum() : "未知专辑");

            // 加载封面
            if (song.getCover() != null && !song.getCover().isEmpty()) {
                Glide.with(this)
                        .load(song.getCover())
                        .placeholder(R.drawable.ic_music_note)
                        .error(R.drawable.ic_music_note)
                        .into(ivCover);
            } else {
                ivCover.setImageResource(R.drawable.ic_music_note);
                android.util.Log.d("SuiJiFragment", "使用默认封面");
            }

            // 添加调试日志
            android.util.Log.d("SuiJiFragment", "API获取到歌曲: " + song.getTitle() +
                    ", 歌手: " + song.getArtist() +
                    ", 封面: " + song.getCover() +
                    ", URL: " + song.getUrl());

            // 检查URL是否有效 - 只在URL有效时显示播放提示
            if (song.getUrl() == null || song.getUrl().isEmpty() || !song.getUrl().startsWith("http")) {
                // 仍然显示歌曲信息，但提示无法播放
                showToast("歌曲 '" + song.getTitle() + "' 暂无播放链接，请点击随机按钮重试");
                return;
            }

            // 只有在有有效URL时才提示可以播放
            showToast("获取到可播放歌曲: " + song.getTitle() + " - " + song.getArtist());
        } else {
            showToast("未获取到歌曲数据");
        }
    }

    @Override
    public void showRecent(List<Song> songs) {
        // 随机页面不需要显示最近播放
    }

    @Override
    public void showToast(String msg) {
        if (getContext() != null) {
            android.widget.Toast.makeText(getContext(), msg, android.widget.Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showLoading() {
        // 显示加载状态
        if (btnRandom != null) {
            btnRandom.setText("加载中...");
            btnRandom.setEnabled(false);
        }
    }

    @Override
    public void hideLoading() {
        // 隐藏加载状态
        if (btnRandom != null) {
            btnRandom.setText("随机播放");
            btnRandom.setEnabled(true);
        }
    }

    /**
     * 播放歌曲 - 跳转到播放页面
     */
    private void playSong(Song song) {
        try {
            android.util.Log.d("SuiJiFragment", "准备跳转到播放页面，歌曲: " + song.getTitle());

            Intent intent = new Intent(getActivity(), MusicPlayerActivity.class);

            // 使用基本数据类型传递
            intent.putExtra("song_title", song.getTitle());
            intent.putExtra("song_artist", song.getArtist());
            intent.putExtra("song_url", song.getUrl());
            intent.putExtra("song_cover", song.getCover());
            intent.putExtra("song_album", song.getAlbum());
            intent.putExtra("song_lyrics", song.getLyrics());

            // 标记为随机播放
            intent.putExtra("isRandom", true);

            // 添加调试信息
            android.util.Log.d("SuiJiFragment", "Intent数据: " +
                    "title=" + song.getTitle() +
                    ", artist=" + song.getArtist() +
                    ", url=" + song.getUrl());

            startActivity(intent);

            // 添加过渡动画
            if (getActivity() != null) {
                getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }

            android.util.Log.d("SuiJiFragment", "成功启动播放页面");

        } catch (Exception e) {
            android.util.Log.e("SuiJiFragment", "启动播放页面失败", e);
            showToast("播放功能暂不可用: " + e.getMessage());
        }
    }
}